package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.enums.SequenceEnum;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.contract.enums.ContractBillEnum;
import org.zpmis.domain.contract.model.ContractBill;
import org.zpmis.domain.contract.qo.AddContractBillQo;
import org.zpmis.domain.contract.qo.ConfirmReceiptQo;
import org.zpmis.domain.contract.qo.ContractBillListQo;
import org.zpmis.domain.contract.service.ContractBillService;
import org.zpmis.domain.contract.vo.ContractBillListVo;
import org.zpmis.domain.sequence.service.SequenceService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-2
 * Time: 14:52:19
 */
@Service
@Slf4j
public class ContractBillWebService extends BaseWebService {
    @Reference
    private ContractBillService contractBillService;

    @Reference
    private SequenceService sequenceService;


    /**
     * 新增合同账单
     * @param addContractBillQo
     */
    public void addContract(AddContractBillQo addContractBillQo) throws BusinessException,Exception{
        //获取登陆人信息
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        int status = addContractBillQo.getStatus() == null ? ContractBillEnum.UNCOLLECTED_STATUS.code() : addContractBillQo.getStatus();
        ContractBill contractBill = ContractBill.builder()
                .contractId(addContractBillQo.getContractId())
                .code(sequenceService.getSequenceNum(SequenceEnum.BILL))
                .name(addContractBillQo.getName())
                .amount(new BigDecimal(addContractBillQo.getAmount()).setScale(4))
                .expectTime(addContractBillQo.getExpectTime())
                .deadlineTime(addContractBillQo.getDeadlineTime())
                //.actualTime(addContractBillQo.getActualTime())
                .createId(adminLoginUser.getId())
                .createPerson(adminLoginUser.getUserName())
                .createTime(Instant.now().toEpochMilli())
                .status(status)
                .isDeleted(ContractBillEnum.NOT_DELETE.code())
                .build();
        //如果新增账单是已收款状态 则直接设置收款人为当前登录用户
        if(status == ContractBillEnum.RECEIVED_STATUS.code()){
            contractBill.setPayeeId(adminLoginUser.getId());
            contractBill.setPayee(adminLoginUser.getUserName());
        }
        contractBillService.save(contractBill);
    }

    /**
     * 合同账单列表查询
     * @param contractBillListQo
     * @return
     * @throws Exception
     */
    public PageInfo contractBillList(ContractBillListQo contractBillListQo) throws Exception{
        Long contractId = contractBillListQo.getContractId();
        String name = contractBillListQo.getName();
        String code = contractBillListQo.getCode();
        Integer status = contractBillListQo.getStatus();
        Long startTime = contractBillListQo.getStartTime();
        Long endTime = contractBillListQo.getEndTime();
        Condition condition = new Condition(ContractBill.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",ContractBillEnum.NOT_DELETE.code());
        if(contractId != null){
            criteria.andEqualTo("contractId",contractId);
        }
        if(status != null){
            criteria.andEqualTo("status",status);
        }
        if(StringUtil.isNotEmpty(code)){
            criteria.andLike("code","%"+code+"%");
        }
        if(StringUtil.isNotEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        condition.orderBy("createTime").desc();
        PageHelper.startPage(contractBillListQo.getPageNum(),contractBillListQo.getPageSize());
        List<ContractBill> contractBillList = contractBillService.findByCondition(condition);
        PageInfo pageInfo = new PageInfo(contractBillList);
        //设置自定义返回结果
        List<ContractBillListVo> resultList = contractBillList.stream().map(ContractBillListVo::new).collect(Collectors.toList());
        pageInfo.setList(resultList);
        return pageInfo;
    }

    /**
     * 合同订单确认收款
     * @param confirmReceiptQo
     * @throws BusinessException
     * @throws Exception
     */
    public void confirmReceipt(ConfirmReceiptQo confirmReceiptQo) throws BusinessException,Exception{
        //获取登录人信息
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        Long id = confirmReceiptQo.getId();
        ContractBill contractBill = contractBillService.findById(id);
        if(contractBill == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        Integer status = contractBill.getStatus();
        //如果已经收款 则不做任何操作
        if(status != ContractBillEnum.RECEIVED_STATUS.code()){
            contractBillService.update(
                    ContractBill.builder()
                    .id(id)
                    .actualTime(confirmReceiptQo.getActualTime())
                    .payeeId(adminLoginUser.getId())
                    .payee(adminLoginUser.getUserName())
                    .status(ContractBillEnum.RECEIVED_STATUS.code())
                    .build()
            );
        }
    }
}
